﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Revit;
using YArchitech.Revit.Electric.Common;
using YArchitech.Revit.RevitExtension;

namespace HYRElectric.Dimension
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class CmdWireDim : YJKCommandManual
	{
		protected override Result YJKExcute(ExternalCommandData cmdData, ref string message, ElementSet elements)
		{
			this.m_doc = cmdData.Application.ActiveUIDocument.Document;
			DlgWireDim dlgWireDim = new DlgWireDim(cmdData.Application);
			dlgWireDim.Show(WindowHelper.HWndRevit);
			WindowHelper.SendMessageToWndRevit();
			Result result;
			for (;;)
			{
				try
				{
					Selection selection = cmdData.Application.ActiveUIDocument.Selection;
					Reference reference = selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, new WireFilter(), "请选择需要标注的导线");
					if (reference != null)
					{
						Wire wire = this.m_doc.GetElementById(reference.ElementId) as Wire;
						Family family = dlgWireDim.SelectDbFamily.Load(this.m_doc);
						if (family == null)
						{
							dlgWireDim.Close();
							result = Autodesk.Revit.UI.Result.Cancelled;
							break;
						}
						FamilySymbol familySymbol = null;
						foreach (FamilySymbol familySymbol2 in family.GetSymbols())
						{
							if (familySymbol2 != null)
							{
								familySymbol = familySymbol2;
								break;
							}
						}
						if (familySymbol == null || familySymbol.Id == null)
						{
							dlgWireDim.Close();
							result = Autodesk.Revit.UI.Result.Cancelled;
							break;
						}
						this.StartTransaction();
						XYZ xyz = selection.PickPoint("请点选标注位置");
						this.AddWireShareParam(this.m_doc, wire);
						if (!this.SetStandardParamValue(dlgWireDim.SelectDbFamily.Name, wire))
						{
							MessageBox.Show("导线缺少标注参数,请使用“设备连线”功能重新连接！", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
							this.RollbackTransaction();
							dlgWireDim.Close();
							result = Autodesk.Revit.UI.Result.Succeeded;
							break;
						}
						WireDimension.DeleteLeadLineGroups(this.m_doc, wire, "导线标记引线ID");
						WireDimension.DeleteTagOfElement(this.m_doc, wire, "导线标记");
						if (dlgWireDim.cbxLeadDim.Checked)
						{
							this.CreatWireTag(cmdData.Application.ActiveUIDocument, reference, xyz, familySymbol);
						}
						else
						{
							this.m_uiDoc.Document.Create.NewTag(this.m_uiDoc.ActiveView, wire, false, 0, 0, xyz).ChangeTypeId(familySymbol.Id);
							wire.GetParameter("导线标记引线ID").Set("");
						}
						this.CommitTransaction();
					}
					continue;
				}
				catch (Exception)
				{
					this.RollbackTransaction();
					dlgWireDim.Close();
					result = Autodesk.Revit.UI.Result.Succeeded;
				}
				break;
			}
			return result;
		}

		public void CreatWireTag(UIDocument uiDoc, Reference refer, XYZ pickPoint, FamilySymbol fs)
		{
			Document document = uiDoc.Document;
            Autodesk.Revit.DB.View activeView = document.ActiveView;
			XYZ xyz = new XYZ(1.0, 0.0, 0.0);
			XYZ globalPoint = refer.GlobalPoint;
			Wire wire = uiDoc.Document.GetElement(refer) as Wire;
			pickPoint = new XYZ(pickPoint.X, pickPoint.Y, globalPoint.Z);
			IndependentTag independentTag = document.Create.NewTag(activeView, wire, false, 0, 0, pickPoint);
			independentTag.ChangeTypeId(fs.Id);
			BoundingBoxXYZ boundingBoxXYZ = independentTag.get_BoundingBox(document.ActiveView);
			Line line = YJKLineEx.YJKGetBound(new XYZ(boundingBoxXYZ.Min.X, boundingBoxXYZ.Min.Y, 0.0), new XYZ(boundingBoxXYZ.Max.X, boundingBoxXYZ.Min.Y, 0.0));
			XYZ xyz2 = (new XYZ(boundingBoxXYZ.Max.X, boundingBoxXYZ.Max.Y, 0.0) - new XYZ(boundingBoxXYZ.Max.X, boundingBoxXYZ.Min.Y, 0.0)) / 2.0;
			if (pickPoint.X < globalPoint.X)
			{
				xyz = new XYZ(-1.0, 0.0, 0.0);
			}
			ElementId elementId = WireDimension.CreatLeadLine(uiDoc, wire, globalPoint, pickPoint, xyz, line.Length, true);
			XYZ xyz3 = (pickPoint + (pickPoint + line.Length * xyz)) / 2.0;
			ElementTransformUtils.MoveElement(document, independentTag.Id, xyz3 - pickPoint);
			ElementTransformUtils.MoveElement(document, independentTag.Id, xyz2);
			wire.GetParameter("导线标记引线ID").Set(elementId.ToString());
		}

		private bool SetStandardParamValue(string selectFamilyName, Wire wire)
		{
			bool result;
			try
			{
				string arg = wire.GetParameter("截面").AsString();
				int num = wire.get_Parameter(BuiltInParameter.RBS_ELEC_WIRE_HOT_ADJUSTMENT).AsInteger();
				int num2 = wire.get_Parameter(BuiltInParameter.RBS_ELEC_WIRE_GROUND_ADJUSTMENT).AsInteger();
				int num3 = wire.get_Parameter(BuiltInParameter.RBS_ELEC_WIRE_NEUTRAL_ADJUSTMENT).AsInteger();
				int num4 = num + num2 + num3;
				string text = string.Format("{0}×{1}", num4, arg);
				wire.GetParameter("规格").Set(text);
				result = true;
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}

		private void AddWireShareParam(Document doc, Wire wire)
		{
			Dictionary<string, ParameterType> dictionary = new Dictionary<string, ParameterType>();
            dictionary.Add("导线标记引线ID", (ParameterType)1);
            dictionary.Add("规格", (ParameterType)1);
			foreach (KeyValuePair<string, ParameterType> keyValuePair in dictionary)
			{
				if (wire.GetParameter(keyValuePair.Key) == null)
				{
					YArchitech.Revit.Electric.Common.SharedParameter.InsertSharedParameter(doc, BuiltInCategory.OST_Wire, "电气数据", dictionary, false);
					break;
				}
			}
		}

		private void StartTransaction()
		{
			this.m_trans = new Transaction(this.m_doc, "LeadTag");
			this.m_trans.Start();
		}

		private void CommitTransaction()
		{
			if (this.m_trans != null)
			{
				this.m_trans.Commit();
			}
		}

		private void RollbackTransaction()
		{
            if (this.m_trans != null && this.m_trans.GetStatus() == (TransactionStatus)1)
			{
				this.m_trans.RollBack();
			}
		}

		private Transaction m_trans;
	}
}
